<template>
  <div class="data-container">
    <div v-if="!isAdmin" class="no-permission">
      <h2>您没有权限查看此页面</h2>
      <button @click="$router.push('/')">返回首页</button>
    </div>
    
    <div v-else class="data-content">
      <div class="header-actions">
        <h2>{{ questionnaire.title }} - 数据统计</h2>
        <button @click="exportReport" class="export-btn">导出报告</button>
      </div>
      
      <div class="statistics-overview">
        <div class="stat-item">
          <h3>总提交次数</h3>
          <p>{{ totalSubmissions }}</p>
        </div>
      </div>

      <div class="question-statistics">
        <div v-for="(question, index) in questionnaire.questions" :key="index" class="question-stat">
          <h3>问题 {{ index + 1 }}: {{ question.topic }}</h3>
          
          <!-- 选择题统计 -->
          <div v-if="question.type === 'radio' || question.type === 'checkbox'" class="chart-container">
            <div class="charts-wrapper">
              <!-- 左侧：进度条和数据 -->
              <div class="stats-section">
                <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-stat">
                  <div class="option-header">
                    <span class="option-text">{{ option }}</span>
                    <div class="option-data">
                      <span class="count">{{ getOptionCount(index, optIndex) }}人</span>
                      <span class="percentage">({{ getOptionPercentage(index, optIndex) }}%)</span>
                    </div>
                  </div>
                  <div class="progress-bar">
                    <div class="progress" 
                         :style="{
                           width: getOptionPercentage(index, optIndex) + '%',
                           backgroundColor: getChartColor(optIndex)
                         }">
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 右侧：饼图 -->
              <div class="pie-chart" :ref="'pieChart' + index"></div>
            </div>
            
            <!-- 底部：横向柱状图 -->
            <div class="bar-chart-horizontal" :ref="'barChart' + index"></div>
          </div>

          <!-- 文本题统计 -->
          <div v-else-if="question.type === 'textarea'" class="text-answers">
            <div class="text-list">
              <div v-for="(answer, ansIndex) in getTextAnswers(index)" :key="ansIndex" class="text-answer">
                <p>{{ answer }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'DataComponent',
  data() {
    return {
      isAdmin: false,
      questionnaire: {},
      answers: [],
      totalSubmissions: 0,
      charts: []
    }
  },
  created() {
    this.checkPermission()
    this.loadData()
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  methods: {
    checkPermission() {
      const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}')
      this.isAdmin = currentUser.isAdmin || false
    },
    loadData() {
      const questionnaireId = this.$route.params.id
      const questionnaires = JSON.parse(localStorage.getItem('questionnaire') || '[]')
      this.questionnaire = questionnaires.find(q => q.id === parseInt(questionnaireId)) || {}
      
      const allAnswers = JSON.parse(localStorage.getItem('questionnaire_answers') || '{}')
      this.answers = allAnswers[questionnaireId] || []
      this.totalSubmissions = this.answers.length
    },
    getOptionCount(questionIndex, optionIndex) {
      return this.answers.filter(answer => {
        const questionAnswer = answer[`Q${questionIndex + 1}answer`]
        if (Array.isArray(questionAnswer)) {
          return questionAnswer.includes(optionIndex)
        } else {
          return questionAnswer === optionIndex
        }
      }).length
    },
    getOptionPercentage(questionIndex, optionIndex) {
      if (this.totalSubmissions === 0) return 0
      return Math.round((this.getOptionCount(questionIndex, optionIndex) / this.totalSubmissions) * 100)
    },
    getTextAnswers(questionIndex) {
      return this.answers
        .map(answer => answer[`Q${questionIndex + 1}answer`])
        .filter(answer => answer && answer.trim() !== '')
    },
    initCharts() {
      this.questionnaire.questions?.forEach((question, index) => {
        if (question.type === 'radio' || question.type === 'checkbox') {
          this.initPieChart(question, index)
          this.initBarChart(question, index)
        }
      })
    },
    initPieChart(question, index) {
      const chartDom = this.$refs[`pieChart${index}`][0]
      const chart = echarts.init(chartDom)
      
      const data = question.options.map((option, optIndex) => ({
        name: option,
        value: this.getOptionCount(index, optIndex),
        itemStyle: {
          color: this.getChartColor(optIndex)
        }
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}人 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          formatter: '{name}'
        },
        series: [
          {
            type: 'pie',
            radius: ['45%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'inside',
              formatter: '{d}%',
              fontSize: 14,
              color: '#fff'
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      }

      chart.setOption(option)
      this.charts.push(chart)
    },
    initBarChart(question, index) {
      const chartDom = this.$refs[`barChart${index}`][0]
      const chart = echarts.init(chartDom)
      
      const data = question.options.map((option, optIndex) => ({
        name: option,
        value: this.getOptionCount(index, optIndex)
      }))

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '8%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01],
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: data.map(item => item.name),
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        series: [
          {
            name: '选择人数',
            type: 'bar',
            data: data.map((item, index) => ({
              value: item.value,
              itemStyle: {
                color: this.getChartColor(index)
              }
            })),
            label: {
              show: true,
              position: 'right',
              formatter: '{c}人'
            },
            barWidth: '40%'
          }
        ]
      }

      chart.setOption(option)
      this.charts.push(chart)
    },
    exportReport() {
      let report = `问卷调查报告\n`
      report += `标题：${this.questionnaire.title}\n`
      report += `总提交次数：${this.totalSubmissions}\n\n`

      this.questionnaire.questions?.forEach((question, index) => {
        report += `问题 ${index + 1}：${question.topic}\n`
        
        if (question.type === 'radio' || question.type === 'checkbox') {
          question.options.forEach((option, optIndex) => {
            const count = this.getOptionCount(index, optIndex)
            const percentage = this.getOptionPercentage(index, optIndex)
            report += `${option}: ${count}人 (${percentage}%)\n`
          })
        } else if (question.type === 'textarea') {
          const answers = this.getTextAnswers(index)
          report += `回答数量：${answers.length}\n`
          answers.forEach((answer, i) => {
            report += `回答 ${i + 1}：${answer}\n`
          })
        }
        report += '\n'
      })

      // 创建并下载文件
      const blob = new Blob([report], { type: 'text/plain;charset=utf-8' })
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${this.questionnaire.title}-统计报告.txt`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
    },
    getChartColor(index) {
      const colors = [
        '#ee7419', '#91cc75', '#fac858', '#5470c6', 
        '#ea7ccc', '#73c0de', '#3ba272', '#fc8452'
      ];
      return colors[index % colors.length];
    }
  },
  beforeUnmount() {
    // 销毁图表实例
    this.charts.forEach(chart => {
      chart.dispose()
    })
  }
}
</script>

<style lang="scss" scoped>
.data-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .export-btn {
      padding: 8px 16px;
      background: #ee7419;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;

      &:hover {
        background: #d65f0a;
      }
    }
  }

  .chart-container {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);

    .charts-wrapper {
      display: flex;
      gap: 30px;
      margin-bottom: 30px;
    }

    .stats-section {
      flex: 1;
      padding-right: 20px;

      .option-stat {
        margin-bottom: 20px;

        .option-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          .option-text {
            color: #333;
            font-size: 14px;
          }

          .option-data {
            .count {
              color: #666;
              margin-right: 5px;
            }
            .percentage {
              color: #999;
            }
          }
        }

        .progress-bar {
          height: 8px;
          background: #f5f5f5;
          border-radius: 4px;
          overflow: hidden;

          .progress {
            height: 100%;
            border-radius: 4px;
            transition: width 0.3s ease;
          }
        }
      }
    }

    .pie-chart {
      width: 400px;
      height: 300px;
    }

    .bar-chart-horizontal {
      height: 300px;
      margin-top: 20px;
    }
  }

  .word-cloud {
    width: 100%;
    height: 300px;
    margin-bottom: 20px;
  }

  .no-permission {
    text-align: center;
    padding: 50px;
    
    h2 {
      color: #ee7419;
      margin-bottom: 20px;
    }
    
    button {
      padding: 10px 20px;
      background: #ee7419;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      
      &:hover {
        background: #d65f0a;
      }
    }
  }

  .data-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);

    h2 {
      margin-bottom: 20px;
      color: #333;
      font-size: 24px;
    }

    .statistics-overview {
      display: flex;
      gap: 20px;
      margin-bottom: 30px;
      
      .stat-item {
        background: #f5f5f5;
        padding: 20px;
        border-radius: 8px;
        text-align: center;
        
        h3 {
          color: #666;
          margin-bottom: 10px;
        }
        
        p {
          font-size: 24px;
          color: #ee7419;
          font-weight: bold;
        }
      }
    }

    .question-statistics {
      .question-stat {
        margin-bottom: 30px;
        
        h3 {
          margin-bottom: 15px;
          color: #333;
        }

        .option-stats {
          .option-stat {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            
            .option-text {
              width: 150px;
              color: #666;
            }

            .progress-bar {
              flex: 1;
              height: 20px;
              background: #f5f5f5;
              border-radius: 10px;
              margin: 0 15px;
              overflow: hidden;

              .progress {
                height: 100%;
                background: #ee7419;
                transition: width 0.3s ease;
              }
            }

            .percentage {
              width: 50px;
              color: #ee7419;
              font-weight: bold;
            }

            .count {
              color: #666;
              margin-left: 10px;
            }
          }
        }

        .text-answers {
          .text-answer {
            background: #f5f5f5;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 4px;
            
            p {
              color: #666;
              margin: 0;
            }
          }
        }
      }
    }
  }
}
</style>
